package com.testdocs.client.project.create;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.uibinder.client.UiTemplate;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.testdocs.client.project.i18n.ProjectConstants;
import com.testdocs.client.validation.ConstraintViolationException;
import com.testdocs.client.validation.FieldConstraint;
import com.testdocs.client.validation.ValidationConstraint;

public class CreateProjectViewImpl extends Composite
	implements CreateProjectView {
	@UiTemplate("CreateProjectView.ui.xml")
	interface SelectProjectViewUiBinder extends
			UiBinder<Widget, CreateProjectViewImpl> {
	}

	private static SelectProjectViewUiBinder uiBinder = GWT
			.create(SelectProjectViewUiBinder.class);
	
	private CreateProjectView.Presenter presenter;
	
	@UiField
	Label createProjectLabel;
	@UiField
	Label projectNameLabel;
	@UiField
	Label versionLabel;
	
	@UiField
	Label projectNameErrorLabel;
	@UiField
	Label versionErrorLabel;
	
	@UiField
	Button createButton;
	
	@UiField
	TextBox projectName;
	@UiField
	TextBox version;
	
	
	private ProjectConstants createProjectConstants = (ProjectConstants) GWT.create(ProjectConstants.class);

	public CreateProjectViewImpl() {
		initWidget(uiBinder.createAndBindUi(this));
		createProjectLabel.setText(createProjectConstants.createProjectLabel());
		projectNameLabel.setText(createProjectConstants.projectNameLabel());
		versionLabel.setText(createProjectConstants.versionLabel());
		createButton.setText(createProjectConstants.create());
	}

	@Override
	public void setPresenter(Presenter presenter) {
		this.presenter = presenter;
	}

	@UiHandler("createButton")
	void handleClick(ClickEvent e) {
		if (presenter != null) {
			clearErrors();
			try {
				presenter.doCreate(projectName.getText(), version.getText());
			} catch (ConstraintViolationException exception) {
				for (ValidationConstraint constraint : exception.getValidationConstraints()) {
					if (constraint instanceof FieldConstraint &&
							((FieldConstraint)constraint).getField().equals("projectName")) {
						projectNameErrorLabel.setText(constraint.getMessage());
					} else if (constraint instanceof FieldConstraint &&
							((FieldConstraint)constraint).getField().equals("versionName")) {
						versionErrorLabel.setText(constraint.getMessage());
					}
				}
			}
		}
	}

	@Override
	public void clearForm() {
		projectName.setText("");
		version.setText("");
		clearErrors();
		projectName.setFocus(true);
	}
	
	public void clearErrors() {
		projectNameErrorLabel.setText("");
		versionErrorLabel.setText("");		
	}
}
